package com.qyhl.webtv.module_live.teletext.nanbu.detail;

import android.Manifest;
import android.annotation.SuppressLint;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Base64;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ToggleButton;

import androidx.annotation.Nullable;
import androidx.cardview.widget.CardView;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.baidu.mobstat.StatService;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.example.sdk.statisticssdk.StatisticsMainInit;
import com.google.android.material.tabs.TabLayout;
import com.gyf.immersionbar.ImmersionBar;
import com.makeramen.roundedimageview.RoundedImageView;
import com.orhanobut.hawk.Hawk;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.DateUtils;
import com.qyhl.webtv.basiclib.utils.MPermissionUtils;
import com.qyhl.webtv.basiclib.utils.NotchSizeUtil;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.constant.ServicePathConstant;
import com.qyhl.webtv.commonlib.entity.intergral.CoinBean;
import com.qyhl.webtv.commonlib.entity.live.ShoppingListBean;
import com.qyhl.webtv.commonlib.entity.live.TeleTextBean;
import com.qyhl.webtv.commonlib.service.ActivitiesService;
import com.qyhl.webtv.commonlib.service.UserService;
import com.qyhl.webtv.commonlib.utils.MShareBoard;
import com.qyhl.webtv.commonlib.utils.action.ActionConstant;
import com.qyhl.webtv.commonlib.utils.action.ActionLogUtils;
import com.qyhl.webtv.commonlib.utils.eventbus.BusFactory;
import com.qyhl.webtv.commonlib.utils.eventbus.Event;
import com.qyhl.webtv.commonlib.utils.push.PushTools;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.qyhl.webtv.commonlib.utils.view.editbar.EditBar;
import com.qyhl.webtv.commonlib.utils.view.editbar.EditBarOnClickListenerImpl;
import com.qyhl.webtv.commonlib.utils.view.video.detailvideo.QYVideoPlayer;
import com.qyhl.webtv.module_live.R;
import com.qyhl.webtv.module_live.R2;
import com.qyhl.webtv.module_live.common.TeleTextInterface;
import com.qyhl.webtv.module_live.teletext.chatroom.TeleTextCommentFragment;
import com.qyhl.webtv.module_live.teletext.content.TeleTextLiveFragment;
import com.qyhl.webtv.module_live.teletext.detail.MediaPlayerManager;
import com.qyhl.webtv.module_live.teletext.detail.TeleTextContract;
import com.qyhl.webtv.module_live.teletext.detail.TeleTextPageAdapter;
import com.qyhl.webtv.module_live.teletext.detail.TeleTextPresenter;
import com.qyhl.webtv.module_live.teletext.detail.popview.TeleTextShopPopView;
import com.qyhl.webtv.module_live.teletext.detail.popview.detail.TeleTextShopDetailPopView;
import com.qyhl.webtv.module_live.teletext.link.TeleTextLinkFragment;
import com.qyhl.webtv.module_live.teletext.newchatroom.NewTeleTextCommentFragment;
import com.qyhl.webtv.module_live.teletext.summary.TeleTextSummaryFragment;
import com.qyhl.webtv.module_live.utils.MediaListManager;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.umeng.analytics.MobclickAgent;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;
import es.dmoral.toasty.Toasty;

@Route(path = ARouterPathConstant.NANBU_LIVE_DETAIL)
public class NanBuLiveDetailActivity extends BaseActivity implements TeleTextContract.TeleTextView, BaseActivity.InputListener {
    @BindView(R2.id.editbar)
    EditBar editbar;
    @BindView(R2.id.video_player)
    QYVideoPlayer videoPlayer;
    @BindView(R2.id.adv_cover)
    ImageView advCover;
    @BindView(R2.id.adv_close)
    ImageView advClose;
    @BindView(R2.id.adv_layout)
    RelativeLayout advLayout;
    @BindView(R2.id.tabLayout)
    TabLayout tabLayout;
    @BindView(R2.id.teletext_vp)
    ViewPager teletextVp;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;
    @BindView(R2.id.tips)
    TextView tips;
    @BindView(R2.id.foreshow_cover)
    ImageView foreshowCover;
    @BindView(R2.id.foreshow_tip)
    TextView foreshowTip;
    @BindView(R2.id.foreshow_time)
    TextView foreshowTime;
    @BindView(R2.id.foreshow_tipBtn)
    ToggleButton foreshowTipBtn;
    @BindView(R2.id.foreshow_title)
    TextView foreshowTitle;
    @BindView(R2.id.foreshow_layout)
    RelativeLayout foreshowLayout;
    @BindView(R2.id.cover)
    ImageView cover;
    @BindView(R2.id.image_layout)
    RelativeLayout imageLayout;
    @BindView(R2.id.video_layout)
    RelativeLayout indexLayout;
    @BindView(R2.id.shop_layout)
    CardView shopLayout;
    @BindView(R2.id.shop_cover)
    RoundedImageView shopCover;
    @BindView(R2.id.shop_title)
    TextView shopTitle;
    @BindView(R2.id.score)
    TextView score;
    @BindView(R2.id.exchange_btn)
    ImageView exchangeBtn;
    @BindView(R2.id.sale_out)
    RoundedImageView saleOut;
    @BindView(R2.id.video_menu)
    RecyclerView menu_recycler;
    @BindView(R2.id.img_title)
    TextView img_title;
    @BindView(R2.id.img_live_tag)
    ImageView img_live_tag;
    @BindView(R2.id.expand_collapse)
    ImageView expandCollapse;
    @BindView(R2.id.video_tips)
    TextView videoTips;
    @BindView(R2.id.text_layout)
    RelativeLayout textLayout;
    @BindView(R2.id.index_view)
    RelativeLayout indexView;
    @BindView(R2.id.index_title)
    TextView indexTitle;
    @BindView(R2.id.index_num)
    TextView indexNum;

    private MediaPlayerManager mediaPlayerManager;

    private TeleTextPresenter mPresenter;

    private String sceneId;

    private TeleTextBean mBean;

    private boolean isBack;

    private boolean editbarEnable = true;

    //是否有聊天室
    private boolean hasChatRoom;

    // Frgaments
    private List<Fragment> mFragmentList;

    private List<String> stringList;

    private ShoppingListBean shopBean;

    @Autowired(name = ServicePathConstant.ACTIVITY_SERVICE)
    public ActivitiesService activitiesService;

    private TeleTextInterface.TeleTextComment commentFragment;
    private TeleTextLinkFragment linkfragment;

    private List<TeleTextBean.MutiAdressList> mDataList = new ArrayList<>();

    private TeleTextShopPopView shopPopView;

    private CommonAdapter<TeleTextBean.MutiAdressList> commonAdapter;

    private Animation animation;
    /**
     * 是否是刘海屏
     */
    private boolean isNotch;

    private boolean isexpand = true;

    private CountDownTimer timer;

    private boolean isFirst = true;

    Timer countTimer = new Timer();
    TimerTask task = new TimerTask() {
        @Override
        public void run() {
            try {
                if (mBean != null) {
                    StatisticsMainInit.tvPlay(CommonUtils.getInstance().getUserName(), mBean.getChatroomId(), mBean.getTitle(), 60);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        isNotch = NotchSizeUtil.hasNotchInScene(this);
        if (!isNotch) {
            if (Build.VERSION.SDK_INT > 19) {
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            }
        }
        ARouter.getInstance().inject(this);

    }

    @Override
    protected int getContentView() {
        return R.layout.live_activity_nanbu_detail;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {

    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @SuppressLint("SetTextI18n")
    @Override
    protected void init() {
        BusFactory.getBus().register(this);
        mPresenter = new TeleTextPresenter(this);
        sceneId = getIntent().getStringExtra("id");

        addInputListener(this);
        loadMask.setStatus(LoadingLayout.Loading);
        stringList = new ArrayList<>();
        mFragmentList = new ArrayList<>();
        //设置动画
        animation = AnimationUtils.loadAnimation(this, R.anim.adv_close);

        menu_recycler.setLayoutManager(new LinearLayoutManager(this, RecyclerView.HORIZONTAL, false));
        menu_recycler.setAdapter(commonAdapter = new CommonAdapter<TeleTextBean.MutiAdressList>(this, R.layout.live_item_nanbu_detail, mDataList) {
            @Override
            protected void convert(ViewHolder holder, TeleTextBean.MutiAdressList bean, int position) {
                if (bean.isChecked()) {
                    holder.setBackgroundRes(R.id.title, R.color.global_base);
                    holder.setText(R.id.title, "正在播放");
                } else {
                    holder.setBackgroundRes(R.id.title, R.color.transparent);
                    holder.setText(R.id.title, bean.getTitle());
                }


            }
        });

        editbar.setShareIconRes(R.drawable.live_nanbu_share_icon)
                .showLike(true)
                .hideShare(false)
                .hideCollect(true)
                .hideComment(true)
                .setCollectIconRes(R.drawable.live_nanbu_collect_icon);

        tips.setText("“" + getString(R.string.app_name) + "”" + "为您直播");

        mPresenter.getDetail(sceneId);
        mPresenter.addClick(sceneId);
    }

    @Override
    protected void setListener() {
        //输入框监听
        editbar.setEditBarOnClickListener(new EditBarOnClickListenerImpl() {
            @Override
            public void onSend() {
                if (editbarEnable) {
                    editbarEnable = false;

                    CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                        @Override
                        public void login(boolean isLogin) {
                            if (isLogin) {
                                final String comment = editbar.getContent();
                                if (StringUtils.isEmpty(comment)) {
                                    Toasty.normal(NanBuLiveDetailActivity.this, "内容不能为空！").show();
                                } else {
                                    for (int i = 0; i < mFragmentList.size(); i++) {
                                        if (mFragmentList.get(i) == commentFragment) {
                                            if (i != teletextVp.getCurrentItem()) {
                                                teletextVp.setCurrentItem(i, true);
                                            }
                                            break;
                                        }
                                    }
                                    commentFragment.sendComment(comment);
                                    editbar.clearContent();
                                    editbar.changeStateDefault(NanBuLiveDetailActivity.this);
                                }
                                editbarEnable = true;
                            } else {
                                Toasty.normal(NanBuLiveDetailActivity.this, "尚未登录或登录已失效！").show();
                                RouterManager.routerLogin(NanBuLiveDetailActivity.this, 0);
                                editbarEnable = true;
                            }
                        }

                        @Override
                        public void error(String s) {

                        }
                    });

                }
                editbar.closeKey(NanBuLiveDetailActivity.this);
            }

            @Override
            public void shopList() {
                if (shopPopView == null) {
                    shopPopView = new TeleTextShopPopView(NanBuLiveDetailActivity.this, sceneId);
                }
                shopPopView.showPopupWindow();
            }

            @Override
            public void doFollow() {
                mPresenter.getPraise(mBean.getId() + "");
            }

            @Override
            public void onShare() {
                MPermissionUtils.requestPermissionsResult(NanBuLiveDetailActivity.this, 1, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, new MPermissionUtils.OnPermissionListener() {
                    @Override
                    public void onPermissionGranted() {
                        if (mBean != null) {
                            MShareBoard shareBoard = new MShareBoard(NanBuLiveDetailActivity.this, mBean.getId() + "", mBean.getTitle(), mBean.getCoverPic(), mBean.getDigest(), CommonUtils.getInstance().getBannerId(), 6);
                            shareBoard.showPopupWindow();
                        } else {
                            Toasty.normal(NanBuLiveDetailActivity.this, "请加载完成后再分享！").show();
                        }
                    }

                    @Override
                    public void onPermissionDenied() {
                        MPermissionUtils.showTipsDialog(NanBuLiveDetailActivity.this);
                    }
                });
            }
        });

        //关闭广告监听
        advClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Animation.AnimationListener aal = new Animation.AnimationListener() {
                    @Override
                    public void onAnimationStart(Animation animation) {

                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {
                        advLayout.setVisibility(View.GONE);
                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {

                    }
                };
                animation.setAnimationListener(aal);
                advLayout.startAnimation(animation);
            }
        });


        //广告链接
        advCover.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String url = mBean.getAdvUrl();
                if (mBean.getAdvUrl() != null && !StringUtils.isEmpty(url)) {
                    Bundle bundle = new Bundle();
                    bundle.putString("url", url);
                    bundle.putBoolean("hasShare", false);
                    RouterManager.router(ARouterPathConstant.ADV, bundle);
                }
            }
        });

        teletextVp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (hasChatRoom) {
                    if (position != 1) {
                        editbar.changeStateDefault(NanBuLiveDetailActivity.this);
                    }
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });


        videoPlayer.getFullscreenButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                videoPlayer.startWindowFullscreen(NanBuLiveDetailActivity.this, true, true);
            }
        });

        videoPlayer.getBackButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (GSYVideoManager.backFromWindowFull(NanBuLiveDetailActivity.this)) {

                } else {
                    finish();
                }
            }
        });

        expandCollapse.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isexpand) {
                    expandCollapse.setImageDrawable(ContextCompat.getDrawable(NanBuLiveDetailActivity.this, R.drawable.teletext_expand));
                    if (mBean.getType().equals("1")) {
                        GSYVideoManager.onPause();
                        videoTips.setVisibility(View.VISIBLE);
                        videoPlayer.setVisibility(View.GONE);
                    } else {
                        indexView.setVisibility(View.VISIBLE);

                        textLayout.setVisibility(View.GONE);
                    }
                } else {
                    GSYVideoManager.onResume();
                    if (mBean.getType().equals("1")) {
                        videoTips.setVisibility(View.GONE);
                        videoPlayer.setVisibility(View.VISIBLE);
                        if (QYVideoPlayer.getPlayMode() == QYVideoPlayer.PlayMode.LIVE) {
                            videoPlayer.startPlayLogic();
                        } else {
                            videoPlayer.onVideoResume();
                        }
                    } else {
                        indexView.setVisibility(View.GONE);

                        textLayout.setVisibility(View.VISIBLE);
                    }
                    expandCollapse.setImageDrawable(ContextCompat.getDrawable(NanBuLiveDetailActivity.this, R.drawable.teletext_collaspe));
                }
                isexpand = !isexpand;
            }
        });

        videoTips.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isexpand = true;
                GSYVideoManager.onResume();
                videoTips.setVisibility(View.GONE);
                videoPlayer.setVisibility(View.VISIBLE);
                if (QYVideoPlayer.getPlayMode() == QYVideoPlayer.PlayMode.LIVE) {
                    videoPlayer.startPlayLogic();
                } else {
                    videoPlayer.onVideoResume();
                }
                expandCollapse.setImageDrawable(ContextCompat.getDrawable(NanBuLiveDetailActivity.this, R.drawable.teletext_collaspe));
            }
        });


        loadMask.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                loadMask.setReloadButtonText("加载中...");
                mPresenter.getDetail(sceneId);
            }
        });

        //提醒开关
        foreshowTipBtn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, final boolean isChecked) {
                if (!isFirst) {

                    CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                        @Override
                        public void login(boolean isLogin) {
                            if (isLogin) {
                                if (isChecked) {
                                    mPresenter.dofollow(sceneId);
                                } else {
                                    mPresenter.unfollow(sceneId);
                                }
                            } else {
                                if (isChecked) {
                                    String str = "Scene_" + CommonUtils.getInstance().getSite() + "_" + sceneId;
                                    ArrayList<Integer> data = Hawk.get("scene_list");
                                    if (data == null) {
                                        data = new ArrayList<>();
                                    }
                                    data.add(Integer.parseInt(sceneId));
                                    Hawk.put("scene_list", data);
                                    PushTools.BindTagByDevice(str);
                                } else {
                                    String str = "Scene_" + CommonUtils.getInstance().getSite() + "_" + sceneId;
                                    ArrayList<Integer> data = Hawk.get("scene_list");
                                    if (data != null) {
                                        for (int i = 0; i < data.size(); i++) {
                                            if (data.get(i) == Integer.parseInt(sceneId)) {
                                                data.remove(i);
                                            }
                                        }
                                        Hawk.put("scene_list", data);
                                    }
                                    PushTools.unBindTagByDevice(str);
                                }
                            }
                        }

                        @Override
                        public void error(String s) {

                        }
                    });
                }
            }
        });

        exchangeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (shopBean != null) {
                    TeleTextShopDetailPopView shopDetailPopView = new TeleTextShopDetailPopView(NanBuLiveDetailActivity.this, shopBean.getId() + "");
                    shopDetailPopView.showPopupWindow();
                }
            }
        });

        commonAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder viewHolder, int position) {
                if (mDataList == null || mDataList.size() < 1) {
                    return;
                }


                for (int i = 0; i < mDataList.size(); i++) {
                    mDataList.get(i).setChecked(i == position);
                }
                commonAdapter.notifyDataSetChanged();
                String url = "";
                if (isBack) {
                    url = new String(Base64.decode(mDataList.get(position).getEncodePlayBackUrl(), Base64.DEFAULT));
                } else {
                    url = new String(Base64.decode(mDataList.get(position).getEncodeHlsUrl(), Base64.DEFAULT));
                }
                videoPlayer.setUp(url, false, mBean.getTitle());
                videoPlayer.getStartButton().performClick();
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder viewHolder, int i) {
                return false;
            }
        });

        videoPlayer.setPlayerListener(new QYVideoPlayer.PlayerListener() {
            @Override
            public void isPlay(boolean isPlay) {
                if (mediaPlayerManager != null) {
                    if (isPlay) {
                        if (!mediaPlayerManager.isPlay()) {
                            mediaPlayerManager.start();
                        }
                    } else {
                        if (mediaPlayerManager.isPlay()) {
                            mediaPlayerManager.pause();
                        }
                    }
                }

            }
        });
    }

    @Override
    public void showkeyboard() {

    }

    @Override
    public void hideKeyboard() {
        editbar.changeStateDefault(this);
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void setDetail(TeleTextBean bean) {
        loadMask.setReloadButtonText("点击重试~~");
        loadMask.setStatus(LoadingLayout.Success);
        mBean = bean;

        if (mBean.getAudioList() != null && mBean.getAudioList().size() > 0) {
            mediaPlayerManager = MediaPlayerManager.getInstance();
            mediaPlayerManager.playSound(mBean.getAudioList());
        }

        indexTitle.setText(bean.getTitle());
        indexNum.setText(StringUtils.isEmpty(mBean.getHits()) ? "0" : mBean.getHits());

        if ("6".equals(mBean.getStatus())) {
            foreshowLayout.setVisibility(View.VISIBLE);
            indexLayout.setVisibility(View.GONE);
            imageLayout.setVisibility(View.GONE);
            foreshowTime.setText("直播将于" + DateUtils.foreShowTime(mBean.getStarttime()));
            foreshowTitle.setText(mBean.getTitle());

            Glide.with(this)
                    .load(mBean.getCoverPic())
                    .apply(new RequestOptions().placeholder(R.drawable.icon_live_no_img).error(R.drawable.icon_live_no_img))
                    .into(foreshowCover);

            CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                @Override
                public void login(boolean isLogin) {
                    if (isLogin) {
                        foreshowTipBtn.setChecked(mBean.getIsFollow() == 1);
                    } else {
                        ArrayList<Integer> data = Hawk.get("scene_list");
                        if (data != null) {
                            for (int i = 0; i < data.size(); i++) {
                                if (data.get(i) == mBean.getId()) {
                                    foreshowTipBtn.setChecked(true);
                                }
                            }
                        } else {
                            foreshowTipBtn.setChecked(false);
                        }
                    }
                }

                @Override
                public void error(String s) {

                }
            });
            isFirst = false;

        } else {
            foreshowLayout.setVisibility(View.GONE);
            if (mBean.getType().equals("1")) {
                indexLayout.setVisibility(View.VISIBLE);
                imageLayout.setVisibility(View.GONE);
                /*
                 * 观看20分钟后获取金币
                 */
                String integralSwitch = CommonUtils.getInstance().getIntergralSwitch();
                if (Hawk.contains("login") && integralSwitch.equals("1")) {
                    timer = new CountDownTimer(20 * 60 * 1000, 1000) {
                        @Override
                        public void onTick(long millisUntilFinished) {

                        }

                        @Override
                        public void onFinish() {
                            String userName = CommonUtils.getInstance().getUserName();
                            mPresenter.getCoin(userName);
                        }
                    }.start();
                }

                if ("7".equals(mBean.getStatus())) {
                    videoPlayer.setMode(QYVideoPlayer.PlayMode.NORMAL);
                    isBack = true;
                } else {
                    videoPlayer.setMode(QYVideoPlayer.PlayMode.LIVE);
                    isBack = false;
                }


                //设置封面
                ImageView imageView = new ImageView(NanBuLiveDetailActivity.this);
                imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                Glide.with(this)
                        .load(mBean.getCoverPic())
                        .apply(new RequestOptions().placeholder(R.drawable.icon_live_no_img).error(R.drawable.icon_live_no_img))
                        .into(imageView);
                videoPlayer.setThumbImageView(imageView);//设置封面图
                videoPlayer.setRotateViewAuto(false);
                videoPlayer.setLockLand(true);
                videoPlayer.setDismissControlTime(5000);
                videoPlayer.setPersonNum(StringUtils.isEmpty(mBean.getHits()) ? "0" : mBean.getHits());
                switch (mBean.getStatus()) {
                    case "7":
                        videoPlayer.setLiveStatusRes(R.drawable.live_nanbu_detail_review_icon);
                        break;
                    case "2":
                        videoPlayer.setLiveStatusRes(R.drawable.live_nanbu_detail_live_icon);
                        break;
                    case "3":
                        videoPlayer.setLiveStatusRes(R.drawable.live_nanbu_detail_end_icon);
                        break;
                }

                //播放器全屏收起监听
                videoPlayer.setStateListener(new QYVideoPlayer.StateListener() {
                    @Override
                    public void state(boolean isShow) {

                    }

                    @Override
                    public void closeRadio() {
                        MediaListManager me = MediaListManager.getIntance();
                        if (me.getTextView() != null) {
                            me.getTextView().endAnimation();
                            me.getTextView().setContent(me.getContentBean().getAudioDuration());
                        }
                        if (me.isPlay()) {
                            //停止播放语音
                            me.release();
                            //停止动画
                            me.getTextView().endAnimation();

                            //恢复时间
                            me.getTextView().setContent(me.getContentBean().getAudioDuration());
                        }
                    }
                });

                videoPlayer.getFullscreenButton().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //第一个true是否需要隐藏actionbar，第二个true是否需要隐藏statusbar
                        videoPlayer.startWindowFullscreen(NanBuLiveDetailActivity.this, true, true);
                    }
                });

                videoPlayer.getBackButton().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        NanBuLiveDetailActivity.this.finish();
                    }
                });


                mDataList.clear();
                mDataList.addAll(mBean.getStreamAdress());
                if (mDataList.size() > 0) {
                    mDataList.get(0).setChecked(true);

                    String url = "";
                    if (isBack) {
                        url = new String(Base64.decode(mDataList.get(0).getEncodePlayBackUrl(), Base64.DEFAULT));
                    } else {
                        url = new String(Base64.decode(mDataList.get(0).getEncodeHlsUrl(), Base64.DEFAULT));
                    }
                    videoPlayer.setUp(url, false, mBean.getTitle());

                    videoPlayer.getStartButton().performClick();
                }
                commonAdapter.notifyDataSetChanged();

                if (mDataList.size() <= 1) {
                    menu_recycler.setVisibility(View.GONE);
                } else {
                    menu_recycler.setVisibility(View.VISIBLE);
                }


                //四川融媒统计
                if (CommonUtils.getInstance().getSite() == 148 || CommonUtils.getInstance().getSite() == 145) {
                    countTimer.schedule(task, 60 * 1000, 60 * 1000);
                }

            } else {
                indexLayout.setVisibility(View.GONE);
                imageLayout.setVisibility(View.VISIBLE);

                switch (mBean.getStatus()) {
                    case "7":
                        img_live_tag.setImageResource(R.drawable.live_nanbu_detail_review_icon);
                        break;
                    case "2":
                        img_live_tag.setImageResource(R.drawable.live_nanbu_detail_live_icon);
                        break;
                    case "3":
                        img_live_tag.setImageResource(R.drawable.live_nanbu_detail_end_icon);
                        break;
                }

                img_title.setText(mBean.getTitle());

                //设置顶部图片
                Glide.with(this)
                        .load(mBean.getCoverPic())
                        .apply(new RequestOptions().placeholder(R.drawable.cover_large_default).error(R.drawable.cover_large_default))
                        .into(cover);
            }
        }


        //设置广告
        if (StringUtils.isEmpty(mBean.getAdvPic())) {
            advLayout.setVisibility(View.GONE);
        } else {
            advLayout.setVisibility(View.VISIBLE);
            Glide.with(this)
                    .load(mBean.getAdvPic())
                    .apply(new RequestOptions().error(R.drawable.adv_group_no_img).placeholder(R.drawable.adv_group_no_img))
                    .into(advCover);

        }


        //设置点赞数
        int likeNum;
        if (StringUtils.isEmpty(mBean.getLove())) {
            likeNum = 0;
        } else {
            likeNum = Integer.parseInt(mBean.getLove());
        }

        editbar.setLikeNum(likeNum);


        //设置tab
        stringList = new ArrayList<>();
        if (mBean.getIsLink() == 1) {
            stringList.add("链接");
            linkfragment = TeleTextLinkFragment.newInstance(mBean.getLinkUrl());
            mFragmentList.add(linkfragment);//直播碎片
        }

        if (mBean.getIsContent() == 1) {
            stringList.add("直播");
            TeleTextLiveFragment fragment = TeleTextLiveFragment.newInstance(mBean.getId() + "", mBean.getType(), true);
            mFragmentList.add(fragment);//直播碎片
        }

        //是否有聊天室
        if (StringUtils.isNotEmpty(mBean.getChatroomId()) && mBean.getIsChatRoom() == 1) {
            stringList.add("互动");
            if ("0".equals(mBean.getChatRoom().getType())) {
                commentFragment = TeleTextCommentFragment.newInstance(mBean.getChatRoom().getChatRoomId(), mBean.getType(),sceneId);
            } else {
                commentFragment = NewTeleTextCommentFragment.newInstance(mBean.getChatRoom().getChatRoomId(), mBean.getType());
            }
            mFragmentList.add((Fragment) commentFragment);//互动碎片
            hasChatRoom = true;

            editbar
                    .hideText(false);

        } else {
            hasChatRoom = false;
            editbar.hideText(true);
        }

        if (mBean.getIsDescription() == 1) {
            stringList.add("介绍");
            mFragmentList.add(TeleTextSummaryFragment.newInstance(mBean.getDigest()));//摘要碎片
        }

        if (mBean.getActId() > 0) {
            stringList.add("投票");

            mFragmentList.add(activitiesService.getPlayerListFragment(mBean.getActId(), (long) 0, 0, 0, 1, 2, true));
        }

        if (mBean.getSurveyActId() > 0) {
            //投票
            stringList.add(bean.getSurveyActName());
            mFragmentList.add(activitiesService.getTeleVoteFragment(mBean.getSurveyActId(), mBean.getId()));
        }

        if (mBean.getIsContent() != 0 || mBean.getIsChatRoom() != 0 || mBean.getIsDescription() != 0 || mBean.getIsLink() != 0) {
            TeleTextPageAdapter mPageAdapter = new TeleTextPageAdapter(getSupportFragmentManager(), mFragmentList);
            mPageAdapter.setData(stringList);

            teletextVp.setAdapter(mPageAdapter);
            teletextVp.setOffscreenPageLimit(mFragmentList.size());
            tabLayout.setupWithViewPager(teletextVp);
        }

        if (mBean.getIsItem() == 1) {
            editbar.showShop(true, mBean.getItemNumber() + "");
            mPresenter.getShopTop(sceneId);
            PushTools.BindTag("shop_" + CommonUtils.getInstance().getSite() + "_" + sceneId);
        } else {
            editbar.showShop(false);
        }

    }

    @Override
    public void setError(String msg) {
        loadMask.setStatus(LoadingLayout.Error);
        loadMask.setErrorText(msg);
        loadMask.setReloadButtonText("点击重试~~");
    }

    @Override
    public void setEmpty(String msg) {
        loadMask.setStatus(LoadingLayout.Empty);
        loadMask.setReloadButtonText("点击重试~~");
        loadMask.setEmptyText(msg);
    }

    @Override
    public void setNetError(String msg) {
        loadMask.setStatus(LoadingLayout.No_Network);
        loadMask.setReloadButtonText("点击重试~~");
        loadMask.setNoNetworkText(msg);
    }

    @Override
    public void praiseSuccess(String msg) {
        Double d = Double.parseDouble(msg);
        editbar.setLikeNum(d.intValue());
    }

    @Override
    public void praiseError(String msg) {
        Toasty.normal(this, msg).show();
    }

    @Override
    public void followSuccess(String msg, String sceneId) {

    }

    @Override
    public void followError(String msg) {

    }

    @Override
    public void unfollowSuccess(String msg, String sceneId) {

    }

    @Override
    public void unfollowError(String msg) {

    }

    @Override
    public void getCoinSuccess(CoinBean bean) {
        Toasty.normal(NanBuLiveDetailActivity.this, "观看直播，获得" + bean.getCoin() + "金币！").show();

    }

    @Override
    public void getCoinFailure(String msg) {
        Log.i("coin_error", msg);
    }

    @Override
    public void setShopTop(ShoppingListBean bean) {
        if (bean != null) {
            shopBean = bean;

            shopLayout.setVisibility(View.VISIBLE);

            shopTitle.setText(bean.getItemName());

            score.setText(bean.getPrice());

            Glide.with(NanBuLiveDetailActivity.this)
                    .load(bean.getItemPic())
                    .apply(new RequestOptions().placeholder(R.drawable.cover_normal_default).error(R.drawable.cover_normal_default))
                    .into(shopCover);

            if (bean.getStatus() == 0) {
                if (bean.getStock() == 0) {
                    exchangeBtn.setImageResource(R.drawable.shop_exchange_btn_off);
                    saleOut.setImageResource(R.drawable.shop_sale_out_icon);
                    saleOut.setVisibility(View.VISIBLE);
                } else {
                    exchangeBtn.setImageResource(R.drawable.shopping_exchange_two_btn);
                    saleOut.setVisibility(View.GONE);
                }
            } else if (bean.getStatus() == 3) {
                exchangeBtn.setImageResource(R.drawable.shop_exchange_btn_off);
                saleOut.setImageResource(R.drawable.shop_sale_overdue_icon);
                saleOut.setVisibility(View.VISIBLE);
            } else {
                exchangeBtn.setImageResource(R.drawable.shop_exchange_btn_off);
                saleOut.setImageResource(R.drawable.shop_sale_off_icon);
                saleOut.setVisibility(View.VISIBLE);
            }
        } else {
            shopLayout.setVisibility(View.GONE);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                //判断是否是输入状态，是则返回初始状态，否则退出
                if (editbar.getType() == EditBar.TYPE_SEND) {
                    editbar.changeStateDefault(NanBuLiveDetailActivity.this);
                    return true;
                } else if (GSYVideoManager.backFromWindowFull(NanBuLiveDetailActivity.this)) {
                    return true;
                } else if (shopPopView != null && shopPopView.isShowing()) {
                    shopPopView.dismiss();
                } else {
                    finish();
                }
            default:
                break;
        }
        return super.onKeyDown(keyCode, event);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getMessage(Event.ShopTopRefresh event) {
        if (event != null) {
            if (event.getMsg().equals("shop_" + CommonUtils.getInstance().getSite() + "_" + sceneId)) {
                mPresenter.getShopTop(sceneId);
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        //baidu
        StatService.onResume(this);
        StatService.onPageStart(this, "图文直播详情");
        //umeng
        MobclickAgent.onPageStart("图文直播详情");
        MobclickAgent.onResume(this);
        if (videoPlayer != null) {
            if (QYVideoPlayer.getPlayMode() == QYVideoPlayer.PlayMode.LIVE) {
                videoPlayer.startPlayLogic();
            } else {
                videoPlayer.onVideoResume();
            }
        }
        ActionLogUtils.getInstance().onResume(this, ActionConstant.TELETEXTDETAIL);

    }

    @Override
    protected void onPause() {
        super.onPause();
        //baidu
        StatService.onPause(this);
        StatService.onPageEnd(this, "图文直播详情");
        //umeng
        MobclickAgent.onPageEnd("图文直播详情");
        MobclickAgent.onPause(this);
        if (videoPlayer != null) {
            videoPlayer.onVideoPause();
        }
        ActionLogUtils.getInstance().onPause(this, ActionConstant.TELETEXTDETAIL);
    }

    @Override
    protected void onStop() {
        super.onStop();
        MediaListManager me = MediaListManager.getIntance();
        if (me.getTextView() != null) {
            me.getTextView().endAnimation();
            me.getTextView().setContent(me.getContentBean().getAudioDuration());
        }
        if (me.isPlay()) {
            //停止播放语音
            me.release();
            //停止动画
            me.getTextView().endAnimation();

            //恢复时间
            me.getTextView().setContent(me.getContentBean().getAudioDuration());
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (videoPlayer != null) {
            videoPlayer.release();
        }

        if (mediaPlayerManager != null) {
            mediaPlayerManager.release();
        }

        if (timer != null) {
            timer.cancel();
        }

        if (countTimer != null) {
            countTimer.cancel();
        }

        if (mBean != null && mBean.getIsItem() == 1) {
            PushTools.unBindTag("shop_" + CommonUtils.getInstance().getSite() + "_" + sceneId);
        }
        BusFactory.getBus().unregister(this);

    }

    @OnClick({R2.id.forecast_back, R2.id.img_back, R2.id.index_back})
    public void onClick(View view) {
        int viewId = view.getId();
        if (viewId == R.id.forecast_back) {
            finish();
        } else if (viewId == R.id.img_back) {
            finish();
        } else if (viewId == R.id.index_back) {
            finish();
        }
    }
}
